package com.yang.testcookie;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

@WebServlet("/tc01")
public class TestCookie01 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        if (req.getCookies() == null || req.getCookies().length == 0) {
            Cookie cookie = new Cookie("name", URLEncoder.encode(req.getParameter("name")));
            cookie.setMaxAge(3*60*60*24);
            resp.addCookie(cookie);
        }else {
            if (req.getCookies() != null) {
                req.getCookies();
                for (Cookie c : req.getCookies()) {
                    System.out.println(c.getName());
                    System.out.println(URLDecoder.decode(c.getValue()));
                    resp.getWriter().write(URLDecoder.decode(c.getValue()));
                }
            }
        }
    }
}
